package cn.powertime.evaluation.facade.impl;

import cn.powertime.evaluation.Constants;
import cn.powertime.evaluation.annotation.Facade;
import cn.powertime.evaluation.entity.CpsCourse;
import cn.powertime.evaluation.entity.CpsUserLearningRecord;
import cn.powertime.evaluation.facade.CpsCourseFacade;
import cn.powertime.evaluation.service.CpsChapterService;
import cn.powertime.evaluation.service.CpsCourseService;
import cn.powertime.evaluation.service.CpsResourceService;
import cn.powertime.evaluation.service.CpsUserLearningRecordService;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.shiro.jwt.TokenUtils;
import cn.powertime.evaluation.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Facade
@Order(2)
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class CpsCourseFacadeImpl implements CpsCourseFacade {

    @Autowired
    private CpsCourseService cpsCourseService;
    @Autowired
    private CpsChapterService cpsChapterService;
    @Autowired
    private CpsResourceService cpsResourceService;
    @Autowired
    private CpsUserLearningRecordService cpsUserLearningRecordService;

    @Override
    public IPage<WebRespCourseListVo> list(ParamPageVo<WebReqCourseSearchVo> vo,Long uid) {
        Page<CpsCourse> page = new Page<>(vo.getPage().getCurrent(), vo.getPage().getSize());
        return cpsCourseService.pageList(page,vo.getParams(),uid);
    }

    @Override
    public List<WebRespChapterListVo> chapterList(Long courseId, Long uid) {
        //增加pv
        CpsCourse cpsCourse = cpsCourseService.getById(courseId);
        long pv = cpsCourse.getCourseWarePv();
        pv++;
        cpsCourse.setCourseWarePv(pv);
        cpsCourse.setUpdateTime(LocalDateTime.now());
        cpsCourseService.updateById(cpsCourse);
        List<WebRespChapterListVo> list = cpsChapterService.chapterList(courseId,uid);
        list.forEach(i->{
            if(StringUtils.equals("0",i.getTempStatus())){
                i.setStudyStatus(0);
            }else{
                int size = Splitter.on(",").splitToList(i.getTempStatus()).size();
                if(i.getNum() == size && i.getTempStatus().indexOf("1") < 0 ){
                    i.setStudyStatus(2);
                }else{
                    i.setStudyStatus(1);
                }
            }
        });
        return getTrees(list);
    }

    @Override
    public List<WebRespCourseResourceListVo> courseResourceList(WebReqResourceVo vo) {
        return cpsResourceService.courseResourceList(vo);
    }



    @Override
    public synchronized boolean record(WebReqRecordVo vo) {
        //Long uid = ShiroUtils.getUserInfo().getId();
        QueryWrapper<CpsUserLearningRecord> recordQueryWrapper = new QueryWrapper<>();
        //recordQueryWrapper.eq("user_id",uid);
        recordQueryWrapper.eq("course_id",vo.getCourseId());
        recordQueryWrapper.eq("chapter_id",vo.getChapterId());
        recordQueryWrapper.eq("section_id",vo.getSectionId());
        recordQueryWrapper.eq("resource_id",vo.getResourceId());
        cpsUserLearningRecordService.remove(recordQueryWrapper);
        CpsUserLearningRecord record = CpsUserLearningRecord.builder()
                .id(IdWorker.getId())
                //.userId(uid)
                .userId(1L)
                .courseId(vo.getCourseId())
                .chapterId(vo.getChapterId())
                .sectionId(vo.getSectionId())
                .resourceId(vo.getResourceId())
                .status(Constants.STATUS_NORMAL)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .schedule(vo.getSchedule())
                .build();
        return cpsUserLearningRecordService.save(record);
    }

//    @Override
//    public IPage<WebRespCourseRecordListVo> recordList(PageVo vo) {
//        Page<CpsCourse> page = new Page<>(vo.getCurrent(), vo.getSize());
//        return cpsCourseService.recordList(page, ShiroUtils.getUserInfo().getId());
//    }

    @Override
    public List<WebRespCourseAllListVo> allList() {
        return cpsCourseService.allList();
    }

    @Override
    public synchronized boolean Apprecord(WebReqRecordVos vo) {
        Long uid = ShiroUtils.getUserInfo().getId();
        QueryWrapper<CpsUserLearningRecord> recordQueryWrapper = new QueryWrapper<>();
        //recordQueryWrapper.eq("user_id",uid);
        recordQueryWrapper.eq("course_id",vo.getCourseId());
        recordQueryWrapper.eq("chapter_id",vo.getChapterId());
        recordQueryWrapper.eq("section_id",vo.getSectionId());
        recordQueryWrapper.eq("resource_id",vo.getResourceId());
        cpsUserLearningRecordService.remove(recordQueryWrapper);
        CpsUserLearningRecord record = CpsUserLearningRecord.builder()
                .id(IdWorker.getId())
                .userId(uid)
                //.userId(1L)
                .courseId(vo.getCourseId())
                .chapterId(vo.getChapterId())
                .sectionId(vo.getSectionId())
                .resourceId(vo.getResourceId())
                .status(Constants.STATUS_NORMAL)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .schedule(vo.getSchedule())
                .build();
        return cpsUserLearningRecordService.save(record);
    }


    private List<WebRespChapterListVo> getTrees(List<WebRespChapterListVo> list) {
        List<WebRespChapterListVo> rootList = list.stream().filter(item -> StringUtils.equals("0", item.getPid()+"")).collect(Collectors.toList());
        for(WebRespChapterListVo root : rootList) {
            getChilds(list,root);
        }
        return rootList;
    }

    private void getChilds(List<WebRespChapterListVo> childList,  WebRespChapterListVo chapter){

        List<WebRespChapterListVo> cList = childList.stream()
                .filter(item -> StringUtils.equals(item.getPid()+"", chapter.getId()+""))
                .collect(Collectors.toList());
        if(cList == null || cList.isEmpty()) {
            return;
        }
        chapter.setChild(cList);

    }

}
